<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
      :disabled="action === 'view'"
    >
      <el-form-item
        v-for="field in formFields"
        :key="field.name"
        :label="field.label"
        :prop="field.name"
        :required="field.required"
      >
        <FieldRenderer
          v-model="formData[field.name]"
          :field="field"
          mode="form"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ action === 'view' ? '关闭' : '取消' }}</el-button>
        <el-button 
          v-if="action !== 'view'"
          type="primary" 
          :loading="loading"
          @click="handleSubmit"
        >
          {{ action === 'create' ? '创建' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { EntityConfig, FieldConfig, EntityData, FormAction } from '@/types/entity'
import { FieldType } from '@/types/entity'
import FieldRenderer from './FieldRenderer.vue'

interface Props {
  modelValue: boolean
  entityConfig: EntityConfig
  action: FormAction
  data?: EntityData
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', data: EntityData): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const formData = ref<EntityData>({})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
  const actionMap = {
    create: '新增',
    update: '编辑',
    view: '查看'
  }
  return `$${r"{actionMap[props.action]}"}$${r"{props.entityConfig.displayName}"}`
})

const formFields = computed(() => {
  return props.entityConfig.fields.filter(field => {
    // 表单中不显示自增主键
    if (field.autoIncrement && props.action === 'create') return false
    // 根据配置决定是否在表单中显示
    return field.showInForm !== false
  })
})

// 表单验证规则
const formRules = computed<FormRules>(() => {
  const rules: FormRules = {}
  
  formFields.value.forEach(field => {
    const fieldRules: any[] = []
    
    // 必填验证
    if (field.required && !field.autoIncrement) {
      fieldRules.push({
        required: true,
        message: `请输入$${r"{field.label}"}`,
        trigger: ['blur', 'change']
      })
    }
    
    // 字符串长度验证
    if (field.type === FieldType.STRING && field.maxLength) {
      fieldRules.push({
        max: field.maxLength,
        message: `$${r"{field.label}"}长度不能超过$${r"{field.maxLength}"}个字符`,
        trigger: ['blur', 'change']
      })
    }
    
    // 数字类型验证
    if ([FieldType.INTEGER, FieldType.LONG, FieldType.DOUBLE, FieldType.BIG_DECIMAL].includes(field.type)) {
      fieldRules.push({
        type: 'number',
        message: `请输入有效的数字`,
        trigger: ['blur', 'change'],
        transform: (value: any) => Number(value)
      })
    }
    
    if (fieldRules.length > 0) {
      rules[field.name] = fieldRules
    }
  })
  
  return rules
})

// 监听数据变化
watch(
  () => props.data,
  (newData) => {
    if (newData) {
      formData.value = { ...newData }
    } else {
      resetForm()
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && props.action === 'create') {
      resetForm()
    }
  }
)

// 重置表单
function resetForm() {
  formData.value = {}
  // 设置默认值
  props.entityConfig.fields.forEach(field => {
    if (field.defaultValue !== undefined) {
      formData.value[field.name] = field.defaultValue
    }
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 处理关闭
function handleClose() {
  visible.value = false
  resetForm()
}

// 处理提交
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 清理数据，移除空值和不需要的字段
    const submitData = { ...formData.value }
    
    // 处理自增主键
    if (props.action === 'create') {
      props.entityConfig.fields.forEach(field => {
        if (field.autoIncrement) {
          delete submitData[field.name]
        }
      })
    }
    
    emit('submit', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 暴露方法
defineExpose({
  resetForm,
  validate: () => formRef.value?.validate()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>